import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author AMPM
 */

public class AliceClient {

	private static final String privateKey = "aaaaaaaa";

	public static void main(String args[]) throws Exception {
		// an object representing this computers IP address
		InetAddress serverAddress = InetAddress.getByName("localhost");
		int serverPortSara = 7896;
		int serverPortBob = 7897;

		// we request to establish a socket connection to a remote server
		Socket socket = new Socket(serverAddress, serverPortSara);

		// get the output stream from the socket
		OutputStream os = socket.getOutputStream();

		requestKeyFromSara(os);

		// get the input stream from the socket
		InputStream is = socket.getInputStream();
		// wrap it in the ObjectInputStream object
		// ObjectInputStream ois = new ObjectInputStream( is );

		ObjectInputStream ois = SymmetricCrypt.decrypt(is, privateKey);
		System.out.println("Received Object Input Stream from Sara");

		long nonce = (Long) ois.readObject();

		System.out.println(nonce);

		String commonKey = (String) ois.readObject();
		String ticket = (String) ois.readObject();

		socket = new Socket(serverAddress, serverPortBob);

		// get the output stream from the socket
		os = socket.getOutputStream();
		System.out.println("A: Sending ticket to Bob..");
		sendTicketToBob(os, ticket);

		// get the input stream from the socket
		is = socket.getInputStream();
		// wrap it in the ObjectOutputStream object
		ois = new ObjectInputStream(is);

		String messageFromBob = (String) ois.readObject();
		String messageFromBobDecrypted = SymmetricCrypt.DecryptString(
				messageFromBob, commonKey);
		System.out.println("Message from Bob: " + messageFromBobDecrypted);
	}

	public static long nonce() {
		
		return System.currentTimeMillis();
		
	}

	public static ObjectOutputStream requestKeyFromSara(OutputStream os)
			throws IOException {

		ObjectOutputStream oos = new ObjectOutputStream(os);

		oos.writeObject(nonce());
		oos.writeObject("A"); // sender
		oos.writeObject("B"); // receiver

		oos.flush();

		return oos;
	}

	public static void sendTicketToBob(OutputStream os, String ticket)
			throws IOException {

		ObjectOutputStream oos = new ObjectOutputStream(os);

		oos.writeObject(ticket);

		oos.flush();

	}

}
